package com.gongpingjialoan.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.sell.PhotoSelectorActivity;
import com.gongpingjialoan.activity.sell.SellPrivateCarDetailActivity;
import com.gongpingjialoan.activity.sell.SellPrivateStepActivity3;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.PhotoModel;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.data.SellPrivateCarBean;
import com.gongpingjialoan.network.UploadCallBack;
import com.gongpingjialoan.utility.PhotoUtil;
import com.gongpingjialoan.utility.UploadUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/2.
 */
public class AddMaintainView extends FrameLayout implements View.OnClickListener {

    private BaseActivity mContext;

    private LinearLayout mLinearLayout;

    public List<PhotoModel> photos;

    private ImageView mImageView;

    private TextView typeTextView;

    private List<String> addMaintains;

    private View popupView, layout_get_pic, layout_take_pic;

    private PopupWindow mPopupWindow;

    private File dir;

    public String car_id = "";

    private List<View> successViews = new ArrayList<>();
    private List<PhotoModel> successNums = new ArrayList<>();

    private boolean uploadImageStatus = true;
    //多少图片需要上传
    private int photo_need_upload = 0;

    public String camearPath;

    private int id;

    private int max;

    public boolean isEdit = true;


    public AddMaintainView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AddMaintainView(Context context) {
        this(context, null);
    }

    public AddMaintainView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = (BaseActivity) context;
        initView();
    }


    private void initView() {
        photos = new ArrayList<>();
        addMaintains = new ArrayList<>();
        popupView = LayoutInflater.from(mContext).inflate(R.layout.add_maintain_popup, null);
        mPopupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setAnimationStyle(R.style.PopupMenu);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());

        LayoutInflater.from(mContext).inflate(R.layout.add_maintain, this);
        mLinearLayout = (LinearLayout) findViewById(R.id.photo_main);
        mImageView = (ImageView) findViewById(R.id.imgView);
        layout_get_pic = popupView.findViewById(R.id.layout_get_pic);
        layout_take_pic = popupView.findViewById(R.id.layout_take_pic);
        typeTextView = (TextView) findViewById(R.id.type);


        mImageView.setOnClickListener(this);
        layout_get_pic.setOnClickListener(this);
        layout_take_pic.setOnClickListener(this);
        dir = new File(mContext.getExternalCacheDir(), "gpj");
        if (!dir.exists()) dir.mkdirs();
    }

    public void setImgVis() {
        mImageView.setVisibility(View.GONE);
    }


    public void setTitle(String title) {
        if (!TextUtils.isEmpty(title)) {
            typeTextView.setVisibility(View.VISIBLE);
            typeTextView.setText(title);
        }
    }


    public void setId(int id) {
        this.id = id;
    }

    public void setMaxNum(int max) {
        this.max = max;
    }


    //详情页添加数据
    public void setData(List<PhotoModel> datas) {
        if (datas.size() == 0) return;
        photos.addAll(datas);
        initPhoto();
    }


    @Override
    public void onClick(View view) {
        if (view == mImageView) {
            if (max > 0) {
                if (photos.size() >= max) {
                    Toast.makeText(mContext, "最多上传" + max + "张图片", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            mPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        } else if (view == layout_get_pic) {
            mPopupWindow.dismiss();
            Intent intent = new Intent(mContext,
                    PhotoSelectorActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            intent.putExtra("id", id);
            if (max > 0) {
                intent.putExtra(PhotoSelectorActivity.KEY_MAX,
                        max - photos.size());
            }
            if (mContext instanceof SellPrivateCarDetailActivity) {
                SellPrivateCarDetailActivity activity = (SellPrivateCarDetailActivity) mContext;
                if (activity.mOffSellPrivateCarDetailFragment.isAdded()) {
                    activity.mOffSellPrivateCarDetailFragment.startActivityForResult(intent, Const.PICK_MAINTAIN);
                }
            } else {
                mContext.startActivityForResult(intent, Const.PICK_MAINTAIN);
            }


        } else if (view == layout_take_pic) {
            mPopupWindow.dismiss();
            camearPath = new File(dir, System.currentTimeMillis() + ".jpg").getAbsolutePath();
            PhotoUtil.getPhotoFromCamera(mContext, id, camearPath);
        }
    }


    public void cameraCallback() {
        mContext.showProgressDialog("图片上传中...");
        PhotoModel photoModel = new PhotoModel();
        photoModel.setOriginalPath(camearPath);
        photoModel.setIsLoading(false);
        photos.add(photoModel);
        initPhoto();
    }


    //获取照片回调
    public void photoCallBack(Intent arg2) {
        mContext.showProgressDialog("图片上传中...");
        if (arg2 != null && arg2.getExtras() != null) {
            List<PhotoModel> datas = (List<PhotoModel>) arg2.getExtras().getSerializable("photos");
            if (datas == null || datas.isEmpty()) {
                Toast.makeText(mContext, "没有选择图片!", Toast.LENGTH_SHORT).show();
                mContext.hidenProgressDialog();
            } else {
                photos.addAll(datas);
                initPhoto();
            }
        }
    }


    private void initPhoto() {
        photo_need_upload = 0;
        uploadImageStatus = true;
        mLinearLayout.removeAllViews();
        addMaintains.clear();
        successViews.clear();
        successNums.clear();
        int photo_count = photos.size();
        for (int i = 0; i < photo_count; i++) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.maintain_item, null);

            ImageView imageView = (ImageView) view.findViewById(R.id.image);
            ImageView delete = (ImageView) view.findViewById(R.id.delete);
            //imageView.setTag(i);
            delete.setTag(R.id.tag_obj, photos.get(i));
            delete.setTag(R.id.tag_view, view);
            if (!isEdit) {
                delete.setVisibility(View.GONE);
            }

            if (photos.get(i).getId() == -1) {
                String newPhotoPath = new File(dir, System.currentTimeMillis() + ".jpg")
                        .getAbsolutePath();
                Bitmap btp = PhotoUtil.getLocalImage(new File(photos.get(i).getOriginalPath()));
                PhotoUtil.saveLocalImageSquare(btp, new File(newPhotoPath));
                Bitmap bitmap = PhotoUtil.getLocalImage(new File(newPhotoPath));
                imageView.setImageBitmap(bitmap);
                if (!photos.get(i).isLoading()) {
                    successViews.add(view);
                    successNums.add(photos.get(i));
                    photo_need_upload++;
                    photos.get(i).setNewPath(newPhotoPath);
                }
            } else {
                Glide.with(mContext).load(photos.get(i).getUploadedUrl()).centerCrop().crossFade().into(imageView);
            }
            delete.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    final PhotoModel photoModel = (PhotoModel) v.getTag(R.id.tag_obj);
                    final View dView = (View) v.getTag(R.id.tag_view);
                    photos.remove(photoModel);
                    mLinearLayout.removeView(dView);
                    if (mContext instanceof SellPrivateStepActivity3) {
                        if (id == 100) {
                            SellPrivateCarBean.getInstance().maintancesPhotoModels = photos;
                        } else if (id == 101) {
                            SellPrivateCarBean.getInstance().insurancePhotoModels = photos;
                        }
                    }
                    if (mContext instanceof SellPrivateCarDetailActivity) {
                        SellPrivateCarDetailActivity activity = (SellPrivateCarDetailActivity) mContext;
                        if (activity.mOffSellPrivateCarDetailFragment.isAdded()) {
                            activity.mOffSellPrivateCarDetailFragment.addImgFromMaintan(id);
                        }
                    }
                }
            });
            mLinearLayout.addView(view);
        }

        //正式上传
        for (int i = 0; i < photo_count; i++) {
            if (photos.get(i).getId() == -1) {
                if (!photos.get(i).isLoading()) {
                    uploadImg(photos.get(i).getNewPath(), photos.get(i));
                }
            }
        }
    }

    public JSONArray getUrls() throws JSONException {
        JSONArray jsonArray = new JSONArray();
        for (PhotoModel model :
                photos) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", "");
            jsonObject.put("url", model.getUploadedUrl());
            jsonArray.put(jsonObject);
        }
        return jsonArray;
    }


    private void uploadImg(String path, final PhotoModel photoModel) {
        if (!uploadImageStatus) {
            return;
        }
        UploadUtils.uploadImage(path, new UploadCallBack() {
            @Override
            public void success(String uri) {
                photoModel.setIsLoading(true);
                photoModel.setUploadedUrl(uri);
                addMaintains.add(uri);

                photo_need_upload--;
                // setPhotoPath(index, photoUrl);
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (photo_need_upload == 0) {
                            mContext.hidenProgressDialog();
                            Toast.makeText(mContext, "上传成功", Toast.LENGTH_SHORT).show();
                            if (mContext instanceof SellPrivateCarDetailActivity) {
                                SellPrivateCarDetailActivity activity = (SellPrivateCarDetailActivity) mContext;
                                if (activity.mOffSellPrivateCarDetailFragment.isAdded()) {
                                    activity.mOffSellPrivateCarDetailFragment.addImgFromMaintan(id);
                                }
                            }
                            successViews.clear();
                        }
                    }
                } );

            }

            @Override
            public void failure() {
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        for (View v : successViews) {
                            mLinearLayout.removeView(v);
                        }
                        for (PhotoModel i : successNums) {
                            photos.remove(i);
                        }
                        successViews.clear();
                        successNums.clear();
                        uploadImageStatus = false;
                        mContext.hidenProgressDialog();
                        Toast.makeText(mContext, "上传失败,请重试", Toast.LENGTH_SHORT).show();
                        photo_need_upload = 0;
                    }
                });

            }
        }, API.uploadPic , "");

    }


}
